package tech.wetech.admin3.util;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import tech.wetech.admin3.config.WxV3PayConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PrivateKey;

public class WxPayHttpClientBuilder {
  private PrivateKey merchantPrivateKey;

  public WxPayHttpClientBuilder() throws IOException {
    this.merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(WxV3PayConfig.getPrivateKey().getBytes("utf-8")));
//    System.out.println("WxV3PayConfig.getPrivateKey()-----\n" + WxV3PayConfig.getPrivateKey());
  }

  public CloseableHttpClient buildClient() throws IOException {
    // 加载平台证书
    AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
      new WechatPay2Credentials(WxV3PayConfig.mchId, new PrivateKeySigner(WxV3PayConfig.mchSerialNo, merchantPrivateKey)),
      WxV3PayConfig.apiV3Key.getBytes("utf-8")
    );

    // 初始化httpClient
    return WechatPayHttpClientBuilder.create()
      .withMerchant(WxV3PayConfig.mchId, WxV3PayConfig.mchSerialNo, merchantPrivateKey)
      .withValidator(new WechatPay2Validator(verifier))
      .build();
  }
}
